package wetalk.software.bupt.com.wetalk.DB;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import wetalk.software.bupt.com.wetalk.DB.DBConfig.DbUpdateListener;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.model.po.Applicant;
import wetalk.software.bupt.com.wetalk.model.po.ChatUser;
import wetalk.software.bupt.com.wetalk.model.po.Group;
import wetalk.software.bupt.com.wetalk.model.po.SearchMessageRecord;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.model.po.WeTalkMsg;
import wetalk.software.bupt.com.wetalk.model.po.WeTalkRecent;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.util.WeTalkUtils;

/**
 * Created by Administrator on 2017/12/14 0014.
 */

public class WeTalkDB {

    private static final  String TAG="XIAOMA?WeTalkDB";
    private static HashMap<String, WeTalkDB> daoMap = new HashMap<String, WeTalkDB>();

    private SQLiteDatabase db;
    private Context mContext;

    /**
     * 创建并打开WetalkDB：默认打开以当前登录用户名为dbName的数据库，建议使用此方法打开数据库
     */
    public static WeTalkDB create(Context context) {
        DBConfig config = new DBConfig();
        config.setContext(context);
        String dbName = UserManager.getInstance(context).getCurrentUserObjectId();
        if (dbName != null && !dbName.equals("")) {
            config.setDbName(dbName);
        }
        return getInstance(config);
    }

    /**
     * 创建指定dbname的数据库 --用于保存登陆过同一设备的多账户的消息
     *
     * @param context
     * @param dbName
     * @param
     * @return BmobDB
     * @throws
     * @Title: create
     * @Description: TODO
     */
    public static WeTalkDB create(Context context, String dbName) {
        DBConfig config = new DBConfig();
        config.setContext(context);
        config.setDbName(dbName);
        return getInstance(config);
    }

    /**
     * 获取实例BmobDB
     *
     * @param daoConfig
     * @return
     */
    public static WeTalkDB getInstance(DBConfig daoConfig) {
        return init(daoConfig);
    }

    private synchronized static WeTalkDB init(DBConfig daoConfig) {
        WeTalkDB dao = daoMap.get(daoConfig.getDbName());
        if (dao == null) {
            dao = new WeTalkDB(daoConfig);
            daoMap.put(daoConfig.getDbName(), dao);
        }
        return dao;
    }

    private WeTalkDB(DBConfig config) {
        if (config == null)
            throw new RuntimeException("dbConfig is null");
        if (config.getContext() == null)
            throw new RuntimeException("android context is null");
        //获取指定dbname的数据库
        this.db = new SqliteDbHelper(config.getContext()
                .getApplicationContext(), config.getDbName(),
                config.getDbVersion(), config.getDbUpdateListener())
                .getWritableDatabase();
    }

    private static final String CHAT_TABLE_NAME = "chat";// 所有的聊天记录均存储在此数据库中：单聊\群聊
    private static final String COLUMN_NAME_ID = "_id";// 自增id
    private static final String COLUMN_NAME_UID = "conversationid";// 会话id：单聊：fromObjectId+toObjectId
    // 群聊：groudId
    private static final String COLUMN_NAME_TOID = "toId";// 该消息接收方id

    private static final String COLUMN_NAME_BELONGID = "belongid";// 该消息是谁发送的：用于和当前登录用户做比较来区分发送/接收
    private static final String COLUMN_NAME_ACCOUNT = "belongaccount";// 消息发送者的账号
    private static final String COLUMN_NAME_BELONGNICK = "belongnick";// 消息发送者的昵称
    private static final String COLUMN_NAME_BELONGAVATAR = "belongavatar";// 消息发送者的头像
    private static final String COLUMN_NAME_TYPE = "msgtype";// 该消息类型---暂时只有Text类型
    private static final String COLUMN_NAME_TIME = "msgtime";// 时间
    private static final String COLUMN_NAME_CONTENT = "content";// 消息内容
    private static final String COLUMN_NAME_ISREADED = "isreaded";// 读取状态：未读// -0、已读状态-1
    private static final String COLUMN_NAME_STATUS = "status";// 发送状态

    // 最近会话表
    private static final String RECENT_TABLE_NAME = "recent";
    private static final String COLUMN_RECENT_ID = "tuid";//targetUid
    private static final String COLUMN_RECENT_USERNAME = "tusername";
    private static final String COLUMN_RECENT_NICK = "tnick";
    private static final String COLUMN_RECENT_AVATAR = "tavatar";
    private static final String COLUMN_RECENT_LASTMESSAGE = "lastmessage";

    /**
     * 创建或检测最近会话表是否已经创建成功
     *
     * @return String
     * @throws
     */
    private void createOrCheckRecentTable(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + RECENT_TABLE_NAME + " ("
                + COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "//
                + COLUMN_RECENT_ID + " TEXT, "// 对方id
                + COLUMN_RECENT_USERNAME + " TEXT, "// 对方的昵称
                + COLUMN_RECENT_NICK + " TEXT, "// 对方的昵称
                + COLUMN_RECENT_AVATAR + " TEXT, "// 对方的头像
                + COLUMN_RECENT_LASTMESSAGE + " TEXT NOT NULL, "// 消息体
                + COLUMN_NAME_TYPE + " INTEGER, "// 类型--目前只有文本类型
                + COLUMN_NAME_TIME + " TEXT); ");
    }


    /**
     * 创建或检测聊天信息表是否已经创建成功
     */
    private void createOrCheckMessageTable(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + CHAT_TABLE_NAME + " ("
                + COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "// _id
                + COLUMN_NAME_UID + " INTEGER, "// 会话id
                + COLUMN_NAME_ACCOUNT + " TEXT, "// 账号
                + COLUMN_NAME_BELONGNICK + " TEXT, "// 昵称
                + COLUMN_NAME_BELONGAVATAR + " TEXT, "// 头像
                + COLUMN_NAME_CONTENT + " TEXT NOT NULL, "// 消息体
                + COLUMN_NAME_TOID + " TEXT NOT NULL, "// 消息体
                + COLUMN_NAME_BELONGID + " TEXT NOT NULL, "// 消息发送者id
                + COLUMN_NAME_ISREADED + " INTEGER, "// 是否未读：0-未读/1-已读
                + COLUMN_NAME_STATUS + " INTEGER, "// 状态
                + COLUMN_NAME_TYPE + " INTEGER, "// 类型--目前只有文本类型
                + COLUMN_NAME_TIME + " TEXT); ");
    }


    public int queryChatTotalCount(String toId) {
        String fromId = UserManager.getInstance(mContext).getCurrentUserObjectId();
        String fromto = fromId + "&" + toId;
        String tofrom = toId + "&" + fromId;
        String sql = "SELECT * from " + CHAT_TABLE_NAME + " WHERE "
                + COLUMN_NAME_UID + " IN ( '" + fromto + "' , '" + tofrom
                + "' )";
        Cursor c = db.rawQuery(sql, null);
        int count = c.getCount();
        if (c != null && !c.isClosed()) {
            c.close();
            c = null;
        }
        return count;
    }


    // 初始化时创建数据库
    class SqliteDbHelper extends SQLiteOpenHelper {

        private DbUpdateListener mDbUpdateListener;
        Context context;

        public SqliteDbHelper(Context context, String name, int version,
                              DbUpdateListener dbUpdateListener) {
            super(context, name, null, version);
            this.mDbUpdateListener = dbUpdateListener;
            this.context = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // 创建聊天表
            createOrCheckMessageTable(db);
            // 创建最近会话表
            //createOrCheckSessionTable(db);
            //创建群组表
            createOrCheckGroupTable(db);
            //添加用户表
            createOrCheckUserTable(db);
            //添加用户表
            createOrCheckFriendsTable(db);
            //recent表
            createOrCheckRecentTable(db);
            //申请人表
            createOrCheckApplicantTable(db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            if (mDbUpdateListener != null) {
                mDbUpdateListener.onUpgrade(db, oldVersion, newVersion);
            } else { // 清空所有的数据信息
                WeTalkDB.create(context).clearAllDbCache();
                // 重新创建
//				db.execSQL(ADD_INVITE_COLUMN);
            }
        }
    }

    /**
     * 数据库升级时,删除所有数据表
     * 用于清空缓存操作--谨慎使用
     *
     * @return
     * @throws
     * @Title: clearAllDbCache
     * @Description: TODO
     * @Title: clearAllDbCache
     * @Description: TODO
     */
    public void clearAllDbCache() {
        Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type ='table' AND name != 'sqlite_sequence'", null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                db.execSQL("DROP TABLE " + cursor.getString(0));
            }
        }
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }

    /**
     * 保存聊天消息 saveMessage
     *
     * @param message
     * @return int
     * @throws
     * @Title: saveMessage
     * @Description: TODO
     */
    public int saveMessage(WeTalkMsg message) {
        int id = -1;
        if (db.isOpen()) {
            ContentValues values = new ContentValues();
            values.put(COLUMN_NAME_CONTENT, message.getContent());
            values.put(COLUMN_NAME_STATUS, message.getStatus());
            values.put(COLUMN_NAME_BELONGAVATAR, message.getBelongAvatar());//也同样更新头像
            if (!checkTargetMsgExist(message.getConversationId(), message.getMsgTime())) {//不存在则插入
                values.put(COLUMN_NAME_UID, message.getConversationId());
                values.put(COLUMN_NAME_TIME, message.getMsgTime());
                values.put(COLUMN_NAME_ISREADED, message.getIsReaded());
                values.put(COLUMN_NAME_TYPE, message.getMsgType());
                values.put(COLUMN_NAME_BELONGID, message.getBelongId());
                values.put(COLUMN_NAME_BELONGNICK, message.getBelongNick());
                values.put(COLUMN_NAME_ACCOUNT, message.getBelongUsername());
                values.put(COLUMN_NAME_TOID, message.getToId());//增加toId
                db.insert(CHAT_TABLE_NAME, null, values);
            } else {//更新指定消息的内容、状态、头像
                String[] args = new String[]{message.getConversationId(), message.getMsgTime()};
                db.update(CHAT_TABLE_NAME, values, COLUMN_NAME_UID + " = ?  AND " + COLUMN_NAME_TIME + " = ? ", args);
            }
            // 插入成功
            Cursor c = db.rawQuery("select last_insert_rowid() from " + CHAT_TABLE_NAME, null);
            if (c.moveToFirst()) {
                id = c.getInt(0);
            }
            if (c != null && !c.isClosed()) {
                c.close();
                c = null;
            }
        }
        return id;
    }

    /**
     * 搜索聊天记录
     */
    public List<SearchMessageRecord> queryMessageRecord(String message) {
        List<SearchMessageRecord> messagerecords = new ArrayList<SearchMessageRecord>();
        String sql = "select user.id,chat.content,user.avatar,user.name,chat.msgtime,count(*) as '条数' from chat,user where chat.content like'" + message + "%" + "'and chat.toId=user.id group by user.id";
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {

            String avatar = c.getString(c.getColumnIndex(COLUMN_USER_AVATAR));
            String userName = c.getString(c.getColumnIndex(COLUMN_USER_NAME));
            String content = c.getString(c.getColumnIndex(COLUMN_NAME_CONTENT));
            long time = c.getLong(c.getColumnIndex(COLUMN_NAME_TIME));
            String targetId = c.getString(c.getColumnIndex(COLUMN_USER_ID));
            String count = c.getString(c.getColumnIndex("条数"));
            SearchMessageRecord item = new SearchMessageRecord(avatar, userName, content, time, targetId, count);
            messagerecords.add(item);
        }

        if (c != null && !c.isClosed()) {
            c.close();
            c = null;
        }
        //Collections.sort(messagerecords);// 按时间降序
        return messagerecords;
    }

    /**
     * 根据用户ID搜索聊天记录
     */
    public List<SearchMessageRecord> queryMessageRecordByID(String targetId, String message) {
        List<SearchMessageRecord> messagerecords = new ArrayList<SearchMessageRecord>();
        String sql = "select content,msgtime from chat where content like'" + message + "%" + "'and toId='" + targetId + "'";
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {

//            String avatar = c.getString(c.getColumnIndex(COLUMN_USER_AVATAR));
//            String userName = c.getString(c.getColumnIndex(COLUMN_USER_NAME));
            String content = c.getString(c.getColumnIndex(COLUMN_NAME_CONTENT));
            long time = c.getLong(c.getColumnIndex(COLUMN_NAME_TIME));
//            String targetId = c.getString(c.getColumnIndex(COLUMN_USER_ID));
//            String count = c.getString(c.getColumnIndex("条数"));
            SearchMessageRecord item = new SearchMessageRecord(content, time);
            messagerecords.add(item);
        }

        if (c != null && !c.isClosed()) {
            c.close();
            c = null;
        }
        //Collections.sort(messagerecords);// 按时间降序
        return messagerecords;
    }

    /**
     * 获取指定聊天对象之间的未读消息数 getUnreadCount
     *
     * @param toId
     * @return int
     * @throws
     * @Title: getUnreadCount
     * @Description: TODO
     */
    public int getUnreadCount(String toId) {
        String fromId = UserManager.getInstance(mContext).getCurrentUserObjectId();
        String fromto = fromId + "&" + toId;
        String tofrom = toId + "&" + fromId;
//		String sql = "SELECT * from " + CHAT_TABLE_NAME + " WHERE "	+ COLUMN_NAME_UID + " IN ( '" + fromto + "' , '" + tofrom+ "' ) AND "
//				+ COLUMN_NAME_ISREADED + " IN ( '" + BmobConfig.STATE_UNREAD_RECEIVED + "' , '" + BmobConfig.STATE_UNREAD
//				+ "' ) ";
        String sql = "SELECT * from " + CHAT_TABLE_NAME + " WHERE " + COLUMN_NAME_UID + " IN ( '" + fromto + "' , '" + tofrom + "' ) AND "
                + COLUMN_NAME_ISREADED + " = " + WeTalkConfig.STATE_UNREAD_RECEIVED;
        Cursor c = db.rawQuery(sql, null);
        int count = c.getCount();
        if (c != null && !c.isClosed()) {
            c.close();
            c = null;
        }
        return count;
    }

    public void resetUnread(String toId) {
        String fromId = UserManager.getInstance(mContext).getCurrentUserObjectId();
        String fromto = fromId + "&" + toId;
        String tofrom = toId + "&" + fromId;
        String[] args = new String[]{fromto, tofrom};
        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME_ISREADED, WeTalkConfig.STATE_READED);
        db.update(CHAT_TABLE_NAME, values, COLUMN_NAME_UID + " in( ?, ? )", args);
    }
    /**删除与指定对象的所有消息
     * @Title: deleteMessages
     * @Description: TODO
     * @param  toid 当前聊天的objectid
     * @return
     * @throws
     */

    /**
     * 查询登陆用户所有会话列表
     *
     * @return List<WeTalkRecent>
     * @throws
     * @Title: queryRecents
     * @Description: TODO
     */
    public List<WeTalkRecent> queryRecents() {
        List<WeTalkRecent> recents = new ArrayList<WeTalkRecent>();
        Cursor c = db.rawQuery("SELECT * from " + RECENT_TABLE_NAME + " ORDER BY " + COLUMN_NAME_TIME, null);
        while (c.moveToNext()) {
            String uid = c.getString(c.getColumnIndex(COLUMN_RECENT_ID));// 一直是对方的uid
            String nick = c.getString(c.getColumnIndex(COLUMN_RECENT_NICK));
            String userName = c.getString(c
                    .getColumnIndex(COLUMN_RECENT_USERNAME));
            String avatar = c.getString(c.getColumnIndex(COLUMN_RECENT_AVATAR));
            long time = c.getLong(c.getColumnIndex(COLUMN_NAME_TIME));
            String message = c.getString(c
                    .getColumnIndex(COLUMN_RECENT_LASTMESSAGE));
            int type = c.getInt(c.getColumnIndex(COLUMN_NAME_TYPE));
            WeTalkRecent item = new WeTalkRecent(uid, userName, nick, avatar,
                    message, time, type);
            recents.add(item);
        }

        if (c != null && !c.isClosed()) {
            c.close();
            c = null;
        }
        Collections.sort(recents);// 按时间降序
        return recents;
    }

    /**
     * 保存本地会话
     *
     * @param recent
     * @return
     * @throws
     * @Title: saveRecent
     * @Description: TODO
     */
    public void saveRecent(WeTalkRecent recent) {
        if (db.isOpen()) {// 数据库已打开并且目标uid之前有存储过消息，更新最后一条消息就行
            ContentValues values = new ContentValues();
            values.put(COLUMN_RECENT_AVATAR, recent.getAvatar());
            values.put(COLUMN_RECENT_NICK, recent.getNick());
            if (!isRecentExist(recent.getTargetid())) {// 不存在
                values.put(COLUMN_RECENT_ID, recent.getTargetid());
                values.put(COLUMN_RECENT_USERNAME, recent.getUserName());
                values.put(COLUMN_NAME_TIME, recent.getTime());
                values.put(COLUMN_RECENT_LASTMESSAGE, recent.getMessage());
                values.put(COLUMN_NAME_TYPE, recent.getType());
                db.insert(RECENT_TABLE_NAME, null, values);
            } else {//存在的话
                values.put(COLUMN_RECENT_LASTMESSAGE, recent.getMessage());
                if (isRecentExist(recent.getTargetid(), String.valueOf(recent.getTime()))) {//更新某一个特定时间的消息
                    db.update(RECENT_TABLE_NAME, values, COLUMN_RECENT_ID + " = ?  AND  " + COLUMN_NAME_TIME + " = ?",
                            new String[]{recent.getTargetid(), String.valueOf(recent.getTime())});
                } else {//更新最后一条消息
                    values.put(COLUMN_NAME_TIME, recent.getTime());
                    values.put(COLUMN_NAME_TYPE, recent.getType());
                    db.update(RECENT_TABLE_NAME, values, COLUMN_RECENT_ID + " = ?",
                            new String[]{recent.getTargetid()});
                }
            }
        }
    }

    /**
     * 检查目标用户id(聊天对象)是否在（recent）数据库中
     *
     * @param targetUid
     * @return boolean
     * @throws
     * @Title: isRecentExist
     * @Description: TODO
     */
    private boolean isRecentExist(String targetUid) {
        String[] args = new String[]{targetUid};
        Cursor c = db.query(RECENT_TABLE_NAME, null, COLUMN_RECENT_ID + "=?",
                args, null, null, null);
        boolean isTrue = false;
        try {
            isTrue = c.moveToFirst();
        } finally {
            if (c != null) {
                c.close();
                c = null;
            }
        }
        return isTrue;
    }

    /**
     * 检查目标用户id指定时间的消息是否在（recent）数据库中
     *
     * @param targetUid
     * @return boolean
     * @throws
     * @Title: isRecentExist
     * @Description: TODO
     */
    private boolean isRecentExist(String targetUid, String msgTime) {
        String[] args = new String[]{targetUid, msgTime};
        Cursor c = db.query(RECENT_TABLE_NAME, null, COLUMN_RECENT_ID + " = ?  AND " + COLUMN_NAME_TIME + " = ?",
                args, null, null, null);
        boolean isTrue = false;
        try {
            isTrue = c.moveToFirst();
        } finally {
            if (c != null) {
                c.close();
                c = null;
            }
        }
        return isTrue;
    }

    /**
     * 删除与指定用户之间的会话记录
     *
     * @param targetUid
     * @return
     * @throws
     * @Title: deleteRecent
     * @Description: TODO
     */
    public void deleteRecent(String targetUid) {
        db.delete(RECENT_TABLE_NAME, COLUMN_RECENT_ID + " = ?", new String[]{targetUid});
    }

    /**
     * 检查指定消息是否存在
     *
     * @param
     * @return
     * @throws
     * @Title: checkTargetMsgExist
     * @Description: TODO
     */
    public boolean checkTargetMsgExist(String conversionId, String msgTime) {
        String[] args = new String[]{conversionId, msgTime};
        Cursor c = db.query(CHAT_TABLE_NAME, null, COLUMN_NAME_UID + " = ?  AND " + COLUMN_NAME_TIME + " = ? ", args, null, null, null);
        boolean isTrue = false;
        try {
            isTrue = c.moveToFirst();
        } finally {
            if (c != null) {
                c.close();
                c = null;
            }
        }
        return isTrue;
    }

    //----------------------------------------申请人表-----------------------------------------------------------
    private static final String TABLE_NAME_APPLICANT = "applicant";
    private static final String COLUMN_APT_MARK = "mark";
    private static final String COLUMN_APT_ID = "id";
    private static final String COLUMN_APT_NAME = "name";
    private static final String COLUMN_APT_AVATAR = "avatar";
    private static final String COLUMN_APT_MESSAGE = "message";
    private static final String COLUMN_APT_STATUS = "status";
    private static final String CREATE_TABLE_APPLICANT = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME_APPLICANT + "("
            + COLUMN_APT_MARK + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_APT_ID + " TEXT,"
            + COLUMN_APT_NAME + " TEXT,"
            + COLUMN_APT_AVATAR + " TEXT,"
            + COLUMN_APT_MESSAGE + " TEXT,"
            + COLUMN_APT_STATUS + " INTEGER);";


    /*
    创建或检查申请人表是否存在
     */
    private void createOrCheckApplicantTable(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_APPLICANT);
    }

    /*
    查找所有申请人,后添加的在前面显示
     */
    public List<Applicant> queryApplicantList() {
        List<Applicant> aptList = new ArrayList<>();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME_APPLICANT + " order by " + COLUMN_APT_MARK + " desc", null);
            while (cursor.moveToNext()) {
                Applicant apt = new Applicant();
                apt.setId(cursor.getString(cursor.getColumnIndex(COLUMN_APT_ID)));
                apt.setName(cursor.getString(cursor.getColumnIndex(COLUMN_APT_NAME)));
                apt.setAvatar(cursor.getString(cursor.getColumnIndex(COLUMN_APT_AVATAR)));
                apt.setMessage(cursor.getString(cursor.getColumnIndex(COLUMN_APT_MESSAGE)));
                apt.setStatus(cursor.getInt(cursor.getColumnIndex(COLUMN_APT_STATUS)));
                aptList.add(apt);
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
        return aptList;
    }



    /*
    查找某个申请人
     */
    public Applicant queryApplicant(String aptId) {
        Applicant apt = null;
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME_APPLICANT + " where " + COLUMN_APT_ID + " = ?", new String[]{aptId});
            if (cursor.moveToFirst()) {
                apt = new Applicant();
                apt.setId(cursor.getString(cursor.getColumnIndex(COLUMN_APT_ID)));
                apt.setName(cursor.getString(cursor.getColumnIndex(COLUMN_APT_NAME)));
                apt.setAvatar(cursor.getString(cursor.getColumnIndex(COLUMN_APT_AVATAR)));
                apt.setMessage(cursor.getString(cursor.getColumnIndex(COLUMN_APT_MESSAGE)));
                apt.setStatus(cursor.getInt(cursor.getColumnIndex(COLUMN_APT_STATUS)));
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
        return apt;
    }

    /*
    添加申请人
     */
    public void addApplicant(Applicant apt) {
        if (db.isOpen()) {
            String[] data = new String[5];
            data[0] = apt.getId();
            data[1] = apt.getName();
            data[2] = apt.getAvatar();
            data[3] = apt.getMessage();
            data[4] = String.valueOf(apt.getStatus());
            db.execSQL("insert into " + TABLE_NAME_APPLICANT + " (" +
                    COLUMN_APT_ID+" ,"+ COLUMN_APT_NAME+" ," + COLUMN_APT_AVATAR+" ," + COLUMN_APT_MESSAGE+" ," + COLUMN_APT_STATUS +
                    ") values (?,?,?,?,?)", data);
        }

    }

    /*
    删除申请人
     */
    public void deleteApplicant(String aptId) {
        if (db.isOpen()) {
            db.execSQL("delete from " + TABLE_NAME_APPLICANT + " where " + COLUMN_APT_ID + " = ?", new String[]{aptId});
        }

    }

    /*
    更改某个申请人
     */
    public void updateApplicant(String aptId) {
        if (db.isOpen()) {
            db.execSQL("update " + TABLE_NAME_APPLICANT + " set " + COLUMN_APT_STATUS + " = ? where "+COLUMN_APT_ID+"= ?", new String[]{"1",aptId});
        }
    }

    //----------------------------------------用户表,改成friends表-----------------------------------------------------------
    private static final String TABLE_NAME_USER = "user";
    private static final String COLUMN_USER_ID = "id";
    private static final String COLUMN_USER_NAME = "name";
    private static final String COLUMN_USER_AVATAR = "avatar";
    private static final String COLUMN_USER_PHONE = "phone";
    private static final String COLUMN_USER_EMAIL = "email";
    private static final String COLUMN_USER_DEPARTMENT = "department";
    private static final String COLUMN_USER_PASSWORD = "password";

    private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME_USER + "("
            + COLUMN_USER_ID + " INTEGER PRIMARY KEY,"
            + COLUMN_USER_NAME + " TEXT,"
            + COLUMN_USER_PASSWORD + " TEXT,"
            + COLUMN_USER_AVATAR + " TEXT,"
            + COLUMN_USER_DEPARTMENT + " TEXT,"
            + COLUMN_USER_PHONE + " TEXT,"
            + COLUMN_USER_EMAIL + " TEXT);";

    private static final String TABLE_NAME_FRIEND = "friends";
    private static final String COLUMN_FRIEND_ID = "id";
    private static final String COLUMN_FRIEND_NAME = "name";
    private static final String COLUMN_FRIEND_AVATAR = "avatar";
    private static final String COLUMN_FRIEND_PHONE = "phone";
    private static final String COLUMN_FRIEND_EMAIL = "email";
    private static final String COLUMN_FRIEND_DEPARTMENT = "department";
    private static final String COLUMN_FRIEND_ISBLACK = "isblack";

    private static final String CREATE_TABLE_FRIENDS = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME_FRIEND + "("
            + COLUMN_FRIEND_ID + " INTEGER PRIMARY KEY, "
            + COLUMN_FRIEND_NAME + " TEXT,"
            + COLUMN_FRIEND_ISBLACK + " TEXT,"
            + COLUMN_FRIEND_AVATAR + " TEXT,"
            + COLUMN_FRIEND_DEPARTMENT + " TEXT,"
            + COLUMN_FRIEND_PHONE + " TEXT,"
            + COLUMN_FRIEND_EMAIL + " TEXT);";

    /**
     * 创建或检查好友表是否存在
     */
    private void createOrCheckFriendsTable(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_FRIENDS);
    }

    /**
     * 创建或检查用户表是否存在
     */
    private void createOrCheckUserTable(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_USER);
    }

    /*
    friends添加一个用户
     */
    public void addFri(User user) {
        if (db.isOpen()) {
            String[] data = new String[7];
            data[0] = user.getUserID();
            data[1] = user.getUserName();
            data[2] = user.getAvatar();
            data[3] = user.getPhone();
            data[4] = user.getEmail();
            data[5] = user.getDepartment();
            data[6]="no";

            db.execSQL("insert into " + TABLE_NAME_FRIEND + " (" +
                    COLUMN_FRIEND_ID + "," +
                    COLUMN_FRIEND_NAME + "," +
                    COLUMN_FRIEND_AVATAR + "," +
                    COLUMN_FRIEND_PHONE + "," +
                    COLUMN_FRIEND_EMAIL + "," +
                    COLUMN_FRIEND_DEPARTMENT + "," +
                    COLUMN_FRIEND_ISBLACK + ") " + "values (?,?,?,?,?,?,?)", data);
        }

    }

    //添加user到user表
    public void addUserTable(User user) {
        if (db.isOpen()) {
            String[] data = new String[7];
            data[0] = user.getUserID();
            data[1] = user.getUserName();
            data[2] = user.getAvatar();
            data[3] = user.getPhone();
            data[4] = user.getEmail();
            data[5] = user.getDepartment();
            data[6]=user.getPassword();
            db.execSQL("insert into " + TABLE_NAME_USER + " (" +
                    COLUMN_FRIEND_ID + "," +
                    COLUMN_FRIEND_NAME + "," +
                    COLUMN_FRIEND_AVATAR + "," +
                    COLUMN_FRIEND_PHONE + "," +
                    COLUMN_FRIEND_EMAIL + "," +
                    COLUMN_FRIEND_DEPARTMENT + "," +
                    COLUMN_USER_PASSWORD + ") " + "values (?,?,?,?,?,?,?)", data);
        }
    }

    /*
    查找所有朋友-friends
     */
    public List<User> queryFriList() {
        List<User> userList = new ArrayList<>();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME_FRIEND, null);

            while (cursor.moveToNext()) {
                User user = new User();
                user.setUserId(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_ID)));
                user.setUserName(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_NAME)));
                user.setPhone(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_PHONE)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_EMAIL)));
                user.setDepartment(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_DEPARTMENT)));
                userList.add(user);
            }

            if (!cursor.isClosed()) {
                cursor.close();
            }
        }

        return userList;
    }

    //查找所有用户
    public List<User> queryUserList() {
        List<User> userList = new ArrayList<>();;
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME_USER, null);

            while (cursor.moveToNext()) {
                User user = new User();
                user.setUserId(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_ID)));
                user.setUserName(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_NAME)));
                user.setPhone(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_PHONE)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_EMAIL)));
                user.setDepartment(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_DEPARTMENT)));
                userList.add(user);
            }

            if (!cursor.isClosed()) {
                cursor.close();
            }
        }
        return userList;
    }

    //删除朋友
    public void delFri(String id){
        if(db.isOpen()){
            db.execSQL("delete from friends where id='"+id+"'");
        }

    }

    public WeTalkMsg getMessage(String conversionId, String msgTime) {
        WeTalkMsg msg = new WeTalkMsg();
        if (this.db != null) {
            String[] args = new String[]{conversionId, msgTime};
            Cursor c = this.db.query("chat", (String[]) null, "conversationid = ?  AND msgtime = ?", args, (String) null, (String) null, (String) null);
            if (c.moveToFirst()) {
                String convertsationId = c.getString(c.getColumnIndex("conversationid"));
                String content = c.getString(c.getColumnIndex("content"));
                String belongId = c.getString(c.getColumnIndex("belongid"));
                String belongavatar = c.getString(c.getColumnIndex("belongavatar"));
                String nick = c.getString(c.getColumnIndex("belongnick"));
                String account = c.getString(c.getColumnIndex("belongaccount"));
                int isReaded = c.getInt(c.getColumnIndex("isreaded"));
                int status = c.getInt(c.getColumnIndex("status"));
                int msgType = c.getInt(c.getColumnIndex("msgtype"));
                String toid = c.getString(c.getColumnIndex("toId"));
                String msgtime = c.getString(c.getColumnIndex("msgtime"));
                msg = new WeTalkMsg("", convertsationId, content, toid, belongId, account, belongavatar, nick, msgtime, Integer.valueOf(msgType), Integer.valueOf(isReaded), Integer.valueOf(status));
            }

            if (c != null && !c.isClosed()) {
                c.close();
                c = null;
            }
        }

        return msg;
    }

    public void saveOrCheckContactList(List<ChatUser> contactList) {
        if (this.db.isOpen()) {
            Iterator var3 = contactList.iterator();

            while (var3.hasNext()) {
                ChatUser user = (ChatUser) var3.next();
                ContentValues values = new ContentValues();
                values.put("nick", user.getNick());
                values.put("username", user.getUserName());
                values.put("avatar", user.getAvatar());
                values.put("isblack", "n");
                if (this.checkIsExists(user.getUserID())) {
                    String[] args = new String[]{user.getUserID()};
                    this.db.update("friends", values, "uid = ? ", args);
                } else {
                    values.put("uid", user.getUserID());
                    this.db.insert("friends", (String) null, values);
                }
            }
        }

    }

    private boolean checkIsExists(String uid) {
        Cursor c = this.db.query("friends", (String[]) null, "uid=?", new String[]{uid}, (String) null, (String) null, (String) null);
        boolean isTrue = false;

        try {
            isTrue = c.moveToFirst();
        } finally {
            if (c != null) {
                c.close();
                c = null;
            }

        }

        return isTrue;
    }

    public void batchAddBlack(List<ChatUser> blackList) {
        int size = blackList.size();

        for (int i = 0; i < size; ++i) {
            ChatUser user = (ChatUser) blackList.get(i);
            if (this.checkIsExists(user.getUserID())) {
                this.addBlack(user.getUserName());
            }
        }

    }

    public void addBlack(String username) {
        ContentValues values = new ContentValues();
        values.put("isblack", "y");
        String[] args = new String[]{username};
        this.db.update("friends", values, "username = ? ", args);
    }

    public List<ChatUser> getContactsWithoutBlack(List<ChatUser> contactList, List<ChatUser> blacklist) {
        List<ChatUser> newUsers = new ArrayList();
        Map<String, ChatUser> blackMap = WeTalkUtils.list2map(blacklist);
        int size = contactList.size();

        for (int i = 0; i < size; ++i) {
            ChatUser friend = (ChatUser) contactList.get(i);
            if (!blackMap.containsKey(friend.getUserID())) {
                newUsers.add(friend);
            }
        }

        return newUsers;
    }

    public void deleteAllContact() {
        if (this.db.isOpen()) {
            this.db.delete("friends", (String) null, (String[]) null);
        }

    }

    public void saveContact(ChatUser user) {
        ContentValues values = new ContentValues();
        values.put("id", user.getUserID());
        values.put("name", user.getUserName());
        values.put("avatar", user.getAvatar());
        values.put("isblack", "n");
        if (this.db.isOpen()) {
            this.db.insert("friends", (String) null, values);
        }

    }

    public List<ChatUser> getContactList() {
        List<ChatUser> users = new ArrayList();
        if (this.db.isOpen()) {
            Cursor cursor = this.db.rawQuery("select * from friends WHERE isblack = ?", new String[]{"no"});

            while (cursor.moveToNext()) {
                String uid = cursor.getString(cursor.getColumnIndex("id"));
                String username = cursor.getString(cursor.getColumnIndex("name"));
                String avatar = cursor.getString(cursor.getColumnIndex("avatar"));
                ChatUser user = new ChatUser();
                user.setUserName(username);
                user.setUserId(uid);
                user.setAvatar(avatar);
                users.add(user);
            }

            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }

        return users;
    }

    public List<ChatUser> getUserList() {
        List<ChatUser> users = new ArrayList();
        if (this.db.isOpen()) {
            Cursor cursor = this.db.query("user",(String[]) null,"",(String[]) null,"","","");

            while (cursor.moveToNext()) {
                String uid = cursor.getString(cursor.getColumnIndex("id"));
                String username = cursor.getString(cursor.getColumnIndex("name"));
                String avatar = cursor.getString(cursor.getColumnIndex("avatar"));
                ChatUser user = new ChatUser();
                user.setUserName(username);
                user.setUserId(uid);
                user.setAvatar(avatar);
                users.add(user);
            }

            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }

        return users;
    }

    public User queryFri(String id) {
        User user = null;
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME_FRIEND + " where " + COLUMN_FRIEND_ID + "= ?", new String[]{id});
            if (cursor.moveToFirst()) {
                user = new User();
                user.setUserId(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_ID)));
                user.setUserName(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_NAME)));
                user.setAvatar(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_AVATAR)));
                user.setPhone(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_PHONE)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_EMAIL)));
                user.setDepartment(cursor.getString(cursor.getColumnIndex(COLUMN_FRIEND_DEPARTMENT)));
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
        return user;
    }

    public User queryUserByid(String id) {
        User user = null;
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME_USER +
                    " where " + COLUMN_USER_ID + "= ?", new String[]{id});
            if (cursor.moveToFirst()) {
                user = new User();
                user.setUserId(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID)));
                user.setUserName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
                user.setAvatar(cursor.getString(cursor.getColumnIndex(COLUMN_USER_AVATAR)));
                user.setPhone(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PHONE)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
                user.setDepartment(cursor.getString(cursor.getColumnIndex(COLUMN_USER_DEPARTMENT)));
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
        return user;
    }

    public User queryFriendByName(String name) {
        User user = null;
        if (db.isOpen()) {
            //从user表中读取，因为friends表保存的是好友
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME_USER + " where " + COLUMN_USER_NAME + "= ?", new String[]{name});
            if (cursor.moveToFirst()) {
                user = new User();
                user.setUserId(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID)));
                user.setUserName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
                user.setAvatar(cursor.getString(cursor.getColumnIndex(COLUMN_USER_AVATAR)));
                user.setPhone(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PHONE)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
                user.setDepartment(cursor.getString(cursor.getColumnIndex(COLUMN_USER_DEPARTMENT)));
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
        return user;
    }

    /*
    查找某个用户,姓名查找
     */
    public User queryUserByName(String name) {
        User user = new User();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME_USER + " where " + COLUMN_USER_NAME + "= ?", new String[]{name});
            if (cursor.moveToFirst()) {
                user.setUserId(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID)));
                user.setUserName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
                user.setAvatar(cursor.getString(cursor.getColumnIndex(COLUMN_USER_AVATAR)));
                user.setPhone(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PHONE)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
                user.setDepartment(cursor.getString(cursor.getColumnIndex(COLUMN_USER_DEPARTMENT)));
                user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
        return user;
    }
    
    /*
    删除所有用户
     */
    public void deleteAllFri() {
        if (db.isOpen()) {
            db.execSQL("delete  from " + TABLE_NAME_FRIEND);
        }

    }
    //--------------------------------------上面是-->friends表---------------------------------------------------


    public void updateContentForTargetMsg(String localPath,WeTalkMsg msg){
        String[] args = new String[] { msg.getConversationId(),msg.getMsgTime()};
        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME_CONTENT, localPath+"&"+msg.getContent());//
        db.update(CHAT_TABLE_NAME, values, COLUMN_NAME_UID + " = ?  AND "+ COLUMN_NAME_TIME + " = ? ", args);
    }


    //查询本地的聊天记录
    public List<WeTalkMsg> queryMessages(String toId, int page) {
//		BmobLog.i("queryMessages-->toId:"+toId);
        String fromId = UserManager.getInstance(mContext).getCurrentUserObjectId();
        List<WeTalkMsg> list = new LinkedList<WeTalkMsg>();
        int num = 10 * (page + 1);
        if (db != null) {
            String fromto = fromId + "&" + toId;
            String tofrom = toId + "&" + fromId;

            String sql = "SELECT * from " + CHAT_TABLE_NAME + " WHERE "
                    + COLUMN_NAME_UID + " IN ( '" + fromto + "' , '" + tofrom
                    + "' ) " + " ORDER BY " + COLUMN_NAME_ID + " DESC LIMIT "
                    + num;

            Cursor c = db.rawQuery(sql, null);
            while (c.moveToNext()) {
                String convertsationId = c.getString(c
                        .getColumnIndex(COLUMN_NAME_UID));
                String content = c.getString(c
                        .getColumnIndex(COLUMN_NAME_CONTENT));
                String belongId = c.getString(c
                        .getColumnIndex(COLUMN_NAME_BELONGID));
                String belongavatar = c.getString(c
                        .getColumnIndex(COLUMN_NAME_BELONGAVATAR));
                String nick = c.getString(c
                        .getColumnIndex(COLUMN_NAME_BELONGNICK));
                String account = c.getString(c.getColumnIndex(COLUMN_NAME_ACCOUNT));
                int isReaded = c.getInt(c.getColumnIndex(COLUMN_NAME_ISREADED));
                int status = c.getInt(c.getColumnIndex(COLUMN_NAME_STATUS));
                int msgType = c.getInt(c.getColumnIndex(COLUMN_NAME_TYPE));
                String toid = c.getString(c.getColumnIndex(COLUMN_NAME_TOID));//这个toid和toId还是不一样的，toId是对方的，而toid有时候却是自己的

                String msgtime = c.getString(c.getColumnIndex(COLUMN_NAME_TIME));
                WeTalkMsg msg = new WeTalkMsg("", convertsationId,
                        content,
                        toid,
                        belongId,
                        account,
                        belongavatar,
                        nick,
                        msgtime,
                        msgType,
                        isReaded,
                        status);
                list.add(msg);
            }

            if (c != null && !c.isClosed()) {
                c.close();
                c = null;
            }
            Collections.reverse(list);// 前后反转一下消息记录
        }
        return list;
    }

    //群组表
    private static final String GROUP_TABLE_NAME = "t_group";
    private static final String COLUMN_NAME_GROUPID = "group_id";
    private static final String COLUMN_NAME_GROUPNAME = "group_name";
    private static final String COLUMN_NAME_GROUPUSERID = "user_id";

    /**
     * 删除所有群组
     */
    public void deleteAllGroup() {
        if (db.isOpen()) {
            db.execSQL("delete  from " + GROUP_TABLE_NAME);
        }
    }
    /**
     * 创建或检查群组表是否已经创建成功
     */
    private void createOrCheckGroupTable(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + GROUP_TABLE_NAME + "("
                + COLUMN_NAME_GROUPID + " TEXT PRIMARY KEY ,  "
                + COLUMN_NAME_GROUPNAME + " TEXT,"
                + COLUMN_NAME_GROUPUSERID + " TEXT);");
    }

    /**
     * 查询所有列表
     */
    public List<Group> queryGroupList() {
        List<Group> groupList = null;
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + GROUP_TABLE_NAME, null);
            if (cursor.moveToFirst()) {
                groupList = new ArrayList<>();
                while (cursor.moveToNext()) {
                    Group group = new Group();
                    group.setGroup_name(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_GROUPNAME)));
                    group.setGroup_id(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_GROUPID)));
                    group.setUser_id(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_GROUPUSERID)));
                    groupList.add(group);
                }
            }

            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
        return groupList;
    }

    /**
     添加一个群组
     */
    public void addGroup(Group group) {
        if (db.isOpen()) {
            String[] data = new String[3];
            data[0] = group.getGroup_id();
            data[1] = group.getGroup_name();
            data[2] = group.getUser_id();

            db.execSQL("insert into " + GROUP_TABLE_NAME + " (" +
                    COLUMN_NAME_GROUPID + "," +
                    COLUMN_NAME_GROUPNAME + "," +
                    COLUMN_NAME_GROUPUSERID + ") " + "values (?,?,?)", data);
        }
    }

    public List<ChatUser> getGroupList() {
        List<ChatUser> users = new ArrayList();
        if (this.db.isOpen()) {
            Cursor cursor = this.db.rawQuery("select * from t_group", new String[]{});

            while (cursor.moveToNext()) {
                String group_id = cursor.getString(cursor.getColumnIndex("group_id"));
                String username = cursor.getString(cursor.getColumnIndex("group_name"));
                //String user_id = cursor.getString(cursor.getColumnIndex("user_id"));
                ChatUser user = new ChatUser();
                user.setUserName(username);//username =group name
                user.setUserId(group_id);
                //user.setAvatar(avatar);
                users.add(user);
            }

            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }

        return users;
    }

    /**
     * 退出群聊
     */
    public void deleteGroup(String groupname) {
        if (db.isOpen()) {
            db.execSQL("delete from " + GROUP_TABLE_NAME + " where " + COLUMN_NAME_GROUPNAME + " = ?", new String[]{groupname});
        }
    }

    /**
     * 通过groupname查询群组
     */
    public Group queryGroupByName(String groupname) {
        Group group = new Group();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + GROUP_TABLE_NAME + " where " + COLUMN_NAME_GROUPNAME + "= ?", new String[]{groupname});
            if (cursor.moveToFirst()) {
                group.setGroup_name(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_GROUPNAME)));
                group.setGroup_id(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_GROUPID)));
                group.setUser_id(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_GROUPUSERID)));
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
        return group;
    }
    /**
     * 修改群组名称
     */
    public void modifyGroupInfo(Group group){
        if(db.isOpen()){
            String[] data = new String[4];
            data[0] = group.getGroup_id();
            data[1] = group.getGroup_name();
            data[2] = group.getUser_id();
            String sql = "UPDATE "+GROUP_TABLE_NAME+" SET "+COLUMN_NAME_GROUPNAME+" ='"+data[1]+"',"+COLUMN_NAME_GROUPUSERID+ "='"+data[2]+"'where "+COLUMN_NAME_GROUPID+"='"+data[0]+"'";
            db.execSQL(sql);
        }
    }

    /**
     *按id查找群组
     */
    public Group queryGroupByID(String TargetID) {
        Group group = new Group();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + GROUP_TABLE_NAME + " where " + COLUMN_NAME_GROUPID + "= ?", new String[]{TargetID});
            if (cursor.moveToFirst()) {
                group.setGroup_name(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_GROUPNAME)));
                group.setGroup_id(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_GROUPID)));
                group.setUser_id(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_GROUPUSERID)));
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
        return group;
    }

}
